package com.yuju.log.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.LogRecord;

import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.mysql.jdbc.Util;
import com.yuju.cache.RedisCache;
import com.yuju.common.Result;
import com.yuju.enums.StatusEnum;
import com.yuju.group.dao.entity.Employee;
import com.yuju.group.model.EmployeeModel;
import com.yuju.group.service.IEmployeeService;
import com.yuju.group.service.impl.EmployeeServiceImpl;
import com.yuju.hotel.model.RoomModel;
import com.yuju.hotel.model.RoomRepairModel;
import com.yuju.hotel.service.IRoomRepairService;
import com.yuju.hotel.service.IRoomService;
import com.yuju.log.model.LogRoomRecordModel;
import com.yuju.log.service.ILogRoomRecordService;
import com.yuju.log.service.IRoomLogService;
import com.yuju.order.enums.RoomOrderStatusEnum;
import com.yuju.order.model.RoomOrderModel;
import com.yuju.order.service.IRoomOrderService;
import com.yuju.order.service.impl.RoomOrderServiceImpl;
import com.yuju.persist.util.IdWorkerInstance;
import com.yuju.util.Utils;
import com.yuju.vo.order.RoomOrderVO;

/**
 * 
 * 类名：RoomLogServiceImpl  <br />
 *
 * 功能：房间日志<br/>
 * 包括：打扫、脏房、维修、换房、走结、退房、夜审
 *
 * @author : xuehj <br />
 * @Date : 2018年1月29日 下午1:45:04  <br />
 * @version : 1.1 <br />
 */
@Service
public class RoomLogServiceImpl implements IRoomLogService {
	private static final Logger logger = LoggerFactory.getLogger(RoomLogServiceImpl.class);
	private static ThreadLocal<String> requestThread = new ThreadLocal<String>();
	@Autowired
	private IRoomService roomService;
	@Autowired
	private IRoomRepairService roomRepairService;
	@Autowired
	private IRoomOrderService roomOrderService;
	@Autowired
	private ILogRoomRecordService logRoomRecordService;
	@Autowired
	private IEmployeeService employeeService;
	/**
	 * 
	 * 功能: 日志记录前<br/>
	 * 
	 * 重写：xuehj <br/>
	 * 
	 * @Date ：2018年1月29日 下午2:01:30<br/>
	 * 
	 * @param path
	 * @param obj <br/>
	 * @see com.yuju.log.service.BaseLogService#before(java.lang.String, com.alibaba.fastjson.JSONObject)
	 */
	@Override
	public void before(String path, JSONObject obj) {
		try {
			//根据房间ID查询修改前的状态 保存到redis
			String roomId = "";
			if(obj.getString("id") != null){
				roomId = obj.getString("id");
			}
			if(obj.getString("roomId") != null){
				roomId = obj.getString("roomId");
			}
			if(obj.getString("roomCode") != null){
				String roomCode = obj.getString("roomCode");
				RoomModel roomModel = new RoomModel();
				roomModel.setRoomCode(roomCode);
				roomModel.setHotelId(obj.getString("hotelId"));
				roomModel.setGroupId(obj.getString("groupId"));
				RoomModel find = roomService.find(roomModel);
				roomId = find.getId();
			}
			String oldRoomId = obj.getString("oldRoomId");
			switch (path) {
				//维修新增
				case "/roomRepair/save":
				//完成维修
				case "/roomRepair/finishRepair":
				{
					JSONArray jsonArray = obj.getJSONArray("roomIds");
					for(int i = 0 ;i < jsonArray.size() ;i++){
						beforeWork(jsonArray.getString(i),oldRoomId);
						break;
					}
				}
				//脏房，打扫
				case "/room/dirtyRoom":
				//走结
				case "/orderAccount/orderAccount":
				//退房
				case "/orderAccount/endSettle":
				//换房
				case "/roomOrder/updateForRoom":
				{
					beforeWork(roomId,oldRoomId);
					break;
				}
				//入住
				case "/roomOrder/edit":
				{
					JSONArray arrays = obj.getJSONArray("listRoomOrder");
				    String jsonText = arrays.toJSONString();
				    List<RoomOrderVO> listRoomOrder = JSON.parseObject(jsonText, new TypeReference<ArrayList<RoomOrderVO>>() {
				    });
				    for(RoomOrderVO roomOrderVo : listRoomOrder){
				    	beforeWork(roomOrderVo.getRoomId(),oldRoomId);
				    }
					break;
				}	
			default:
				break;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

	private void beforeWork(String roomId ,String oldRoomId){
		try {
			System.err.println("===================Before房间日志服务开始===================");
			if(oldRoomId == null){
				
				//查询是否脏房
				String dirty = this.isDirty(roomId);
				//查询是否在住
				String live = this.isLive(roomId);
				//查询是否维修
				String repair = this.isRepair(roomId);
				//拼接状态
				String status = dirty + "、" + live + "、" + repair;
				String requestId = IdWorkerInstance.getIdStr();
				requestThread.set(requestId);
				// 查询房间改变之前的状态放到redis中
				RedisCache.getInstance().addCache(requestThread.get(),status.substring(0, status.length() - 1));
			} else {
				//换房的情况
				
				//查询是否脏房
				String dirty = this.isDirty(roomId);
				//查询是否在住
				String live = this.isLive(roomId);
				//查询是否维修
				String repair = this.isRepair(roomId);
				//拼接状态
				String status = dirty + "、" + live + "、" + repair ;
				
				//查询是否脏房
				String oldDirty = this.isDirty(oldRoomId);
				//查询是否在住
				String oldLive = this.isLive(oldRoomId);
				//查询是否维修
				String oldRepair = this.isRepair(oldRoomId);
				//拼接状态
				String oldRoomStatus = oldDirty + "、" + oldLive + "、" + oldRepair ;
				
				Map<String, String> map = new HashMap<>();
				map.put("roomStatus", status.substring(0, status.length() - 1));
				map.put("oldRoomStatus", oldRoomStatus.substring(0, status.length() - 1));
				
				String requestId = IdWorkerInstance.getIdStr();
				requestThread.set(requestId);
				// 查询房间改变之前的状态放到redis中
				RedisCache.getInstance().addCache(requestThread.get(),map);
			}
			System.err.println("===================Before房间日志服务结束===================");
		} catch(Exception e) {
			logger.error("日志报错了：" + e);
		}
	}
	/**
	 * 
	 * 功能: 房间日志记录实现<br/>
	 * 
	 * 重写：xuehj <br/>
	 * 
	 * @Date ：2018年1月29日 下午1:49:53<br/>
	 * 
	 * @param path
	 * @param obj
	 * @param ret <br/>
	 * @see com.yuju.log.service.IRoomLogService#log(java.lang.String, com.alibaba.fastjson.JSONObject, com.yuju.common.Result)
	 */
	@Override
	public void log(String path, JSONObject obj, Result ret) {
		try{
			//根据房间ID查询改变后的状态
			String roomId = "";
			if(obj.getString("id") != null){
				roomId = obj.getString("id");
			}
			if(obj.getString("roomId") != null){
				roomId = obj.getString("roomId");
			}
			String oldRoomId = obj.getString("oldRoomId");
			//获取操作人信息
			String userName = "";
			if(obj.getString("empId") != null){
				EmployeeModel employeeModel = new EmployeeModel();
				employeeModel.setId(obj.getString("empId"));
				EmployeeModel find = employeeService.find(employeeModel);
				userName = find.getName();
			}
			
			String empId = obj.getString("empId");
			
			String remark = obj.getString("remark");
			switch (path) {
				//维修新增
				case "/roomRepair/save":
				//完成维修
				case "/roomRepair/finishRepair":
				{
					JSONArray jsonArray = obj.getJSONArray("roomIds");
					for(int i = 0 ;i < jsonArray.size() ;i++){
						logWork(jsonArray.getString(i),oldRoomId,userName,empId,remark);
						break;
					}
				}
				//脏房，打扫
				case "/room/dirtyRoom":
				//走结
				case "/orderAccount/orderAccount":
				//退房
				case "/orderAccount/endSettle":
				//换房
				case "/roomOrder/updateForRoom":
				
				{
					logWork(roomId,oldRoomId,userName,empId,remark);
					break;
				}
				//入住
				case "/roomOrder/edit":
				{
					JSONArray arrays = obj.getJSONArray("listRoomOrder");
				    String jsonText = arrays.toJSONString();
				    List<RoomOrderVO> listRoomOrder = JSON.parseObject(jsonText, new TypeReference<ArrayList<RoomOrderVO>>() {
				    });
				    for(RoomOrderVO roomOrderVo : listRoomOrder){
				    	logWork(roomOrderVo.getRoomId(),oldRoomId,userName,empId,remark);
				    }
					break;
				}	
			default:
				break;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	private void logWork(String roomId , String oldRoomId ,String userName ,String empId ,String remark){
		try {
			System.err.println("===================房间日志服务开始===================");
			if(oldRoomId == null){
				
				//查询是否脏房
				String dirty = this.isDirty(roomId);
				//查询是否在住
				String live = this.isLive(roomId);
				//查询是否维修
				String repair = this.isRepair(roomId);
				//拼接状态
				String status = dirty + "、" + live + "、" + repair ;
				//从redis取出原状态
				String oldStatus = (String) RedisCache.getInstance().get(requestThread.get());
				
				//获取房间编号
				RoomModel findById = roomService.findById(roomId);
				String roomCode = findById.getRoomCode();
				//执行日志保存操作
				LogRoomRecordModel logRoomRecordModel = new LogRoomRecordModel();
				logRoomRecordModel.setId(Utils.getUUID());
				logRoomRecordModel.setRoomId(roomId);
				logRoomRecordModel.setRoomCode(roomCode);
				logRoomRecordModel.setCreateUserId(empId);
				logRoomRecordModel.setCreateUserName(userName);
				logRoomRecordModel.setOldStatusDesc(oldStatus);
				logRoomRecordModel.setStatusDesc(status.substring(0, status.length() - 1));
				logRoomRecordModel.setGmtCreate(new Date());
				logRoomRecordModel.setGmtModified(new Date());
				logRoomRecordModel.setRemark(remark);
				logRoomRecordService.save(logRoomRecordModel);
			} else {
				//换房的情况
				
				//查询是否脏房
				String dirty = this.isDirty(roomId);
				//查询是否在住
				String live = this.isLive(roomId);
				//查询是否维修
				String repair = this.isRepair(roomId);
				//拼接状态
				String status = dirty + "、" + live + "、" + repair ;
				
				//从redis取出原状态
				Map<String, String> map = (Map<String, String>) RedisCache.getInstance().get(requestThread.get());
				
				//获取房间编号
				RoomModel findById = roomService.findById(roomId);
				String roomCode = findById.getRoomCode();
				
				//新房间日志添加
				LogRoomRecordModel logRoomRecordModel = new LogRoomRecordModel();
				logRoomRecordModel.setId(Utils.getUUID());
				logRoomRecordModel.setRoomId(roomId);
				logRoomRecordModel.setRoomCode(roomCode);
				logRoomRecordModel.setCreateUserId(empId);
				logRoomRecordModel.setCreateUserName(userName);
				logRoomRecordModel.setOldStatusDesc(map.get("roomStatus"));
				logRoomRecordModel.setStatusDesc(status.substring(0, status.length() - 1));
				logRoomRecordModel.setGmtCreate(new Date());
				logRoomRecordModel.setGmtModified(new Date());
				logRoomRecordModel.setRemark(remark);
				logRoomRecordService.save(logRoomRecordModel);
				
				//新房间状态日志添加
				
				//查询是否脏房
				String oldDirty = this.isDirty(oldRoomId);
				//查询是否在住
				String oldLive = this.isLive(oldRoomId);
				//查询是否维修
				String oldRepair = this.isRepair(oldRoomId);
				//拼接状态
				String oldStatus = oldDirty + "、" + oldLive + "、" + oldRepair ;
				
				//获取房间编号
				RoomModel oldFindById = roomService.findById(oldRoomId);
				String oldRoomCode = oldFindById.getRoomCode();
				
				//原房间日志添加
				logRoomRecordModel.setId(Utils.getUUID());
				logRoomRecordModel.setRoomId(oldRoomId);
				logRoomRecordModel.setRoomCode(oldRoomCode);
				logRoomRecordModel.setCreateUserId(empId);
				logRoomRecordModel.setCreateUserName(userName);
				logRoomRecordModel.setOldStatusDesc(map.get("oldRoomStatus"));
				logRoomRecordModel.setStatusDesc(oldStatus.substring(0, status.length() - 1));
				logRoomRecordModel.setGmtCreate(new Date());
				logRoomRecordModel.setGmtModified(new Date());
				logRoomRecordModel.setRemark(remark);
				logRoomRecordService.save(logRoomRecordModel);
			}
			
			System.err.println("===================房间日志服务结束===================");
		} catch(Exception e) {
			logger.error("日志报错了,路径：" + e);
		}
	}
	
	/**
	 * 
	 * 功能：查询是否空房<br/>
	 *
	 * @author zhousc
	 * @Date 2018年1月30日 上午10:35:02 <br/>
	 */
	private String isLive(String roomId){
		RoomOrderModel roomOrderModel = new RoomOrderModel();
		roomOrderModel.setRoomId(roomId);
		roomOrderModel.setCheckinStatus(RoomOrderStatusEnum.CHECKIN.getValue());
		RoomOrderModel find = roomOrderService.find(roomOrderModel);
		if(find == null){
			return "空";
		}else{
			return "住";
		}
	}
	
	/**
	 * 
	 * 功能：查询是否脏房<br/>
	 *
	 * @author zhousc
	 * @Date 2018年1月30日 上午10:36:54 <br/>
	 */
	private String isDirty(String roomId) {
		RoomModel findById = roomService.findById(roomId);
		//判断当前状态
		if(findById.getIsDirty().equals(StatusEnum.TRUE.getValue())){
			return "脏";
		} else {
			return "净";
		}
		
	}
	
	/**
	 * 
	 * 功能：查询是否维修<br/>
	 *
	 * @author zhousc
	 * @Date 2018年1月30日 上午10:39:16 <br/>
	 */
	private String isRepair(String roomId) {
		RoomRepairModel roomRepairModel = new RoomRepairModel();
		roomRepairModel.setRoomId(roomId);
		Byte selectRepairStatus = roomRepairService.selectRepairStatus(roomRepairModel);
		//判断当前状态
		if(selectRepairStatus.equals(StatusEnum.TRUE.getValue())){
			return "维修、";
		} else {
			return "";
		}
	}

}
